package a08_回溯算法;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;

/**
 * <p>
 * a08_组合总和2
 * </p>
 *
 * //此题意思为：113    4
 * 只能出现13
 * 如果不去重：13,13
 *
 * 树层去重、树枝去重
 * 1,2,1   3
 * 先排序1,1,2   3
 *
 * 树层去重：从第一个1开始的集合，肯定包含第二个1开始的集合
 * 1(第一个1),2   1(第二个1),2
 *
 * @author flyduck
 * @since 2025-01-01
 */
public class a08_组合总和2 {

    public static void main(String[] args) {
        int[] nums = new int[]{1,1,3};
        a08_组合总和2 test = new a08_组合总和2();
        List<List<Integer>> lists = test.combinationSum2(nums, 4);
        System.out.println(lists);
    }

    public List<List<Integer>> combinationSum2(int[] candidates, int target) {
        List<List<Integer>> resultList = new ArrayList<>();
        LinkedList<Integer> path = new LinkedList<>();
        Arrays.sort(candidates);//*
        int[] used = new int[candidates.length];
        traversal(resultList, path, candidates, target, 0, used,0);
        return resultList;
    }

    private void traversal(List<List<Integer>> result,
                           LinkedList<Integer> path,
                           int[] candidates,
                           int targetSum,
                           int sum,
                           int[] used,
                           int startIdx){
        if(sum > targetSum){
            return;
        }
        if(sum == targetSum){
            result.add(new ArrayList<>(path));
            return;
        }

        for (int i = startIdx; i < candidates.length; i++) {
            //112
            //去重 *
            //used[i - 1] == 0说明时树层出现重复，退出
            //used[i - 1] == 1说明时树枝出现重复，继续往下
            if(i > 0 && candidates[i] == candidates[i-1] && used[i - 1] == 0){
                continue;
            }

            path.add(candidates[i]);
            sum = sum + candidates[i];
            used[i] = 1;
            traversal(result, path, candidates, targetSum, sum, used,i + 1);//*
            used[i] = 0;
            path.removeLast();
            sum = sum - candidates[i];
        }

    }
}
